local skynet = require "skynet"
local log = require "Log"
local parser = require "parser"
local protobuf = require "protobuf"
local sharedata = require "sharedata"
local pack_helper = require "pack_helper"

local dir_list = dir_list

local pbc_helper = {}
local function load( protofile , protopath)
	local ok, result = x_pcall(parser.register, protofile, protopath)
	if not ok then
		log.fatal("protobuff init:", result,protofile)
		return nil
	else
		--print("___###########_",protofile)
	end
end

local function cache_message( )
	local message = {}
	for pack_name,field in pairs(parser.cache_fields) do
		local pack_id = pack_helper.get_pack(pack_name)
		if pack_id then
			for msg_name,msg_id in pairs(field) do
				local msg = message[msg_name]
				assert(not msg,'____error__double message '..tostring(msg)..' '..tostring(pack_name))
				message[msg_name] = {pack_name,pack_id}
			end
		end
	end
	sharedata.new('message', message)
end

function pbc_helper.init( path, dirs )
	if not dirs then dirs = {''} end
	for k,dir in ipairs(dirs) do
		local dir_path = path..dir
		local file_list = dir_list(dir_path)
		load(file_list, dir_path)
	end
	cache_message()
	return protobuf.get_protobuf_env()
end

return pbc_helper